package com.process.demo.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 2018/4/13 15:00
 * <h3>Copyright</h3> Copyright (c)2018 Shenzhen TL  Co., Ltd. Inc. All rights reserved.
 */
public class SocketClient {
    private static PrintWriter pw=null;
    private static BufferedReader br=null;
    private static Socket s;
    private static int count = 0;
    private static ScheduledExecutorService executorService  = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) {
        try {
            System.out.print("开启客户端!");
            InetAddress inetAddress  = InetAddress.getLocalHost();
            //创建一个流套接字并将其连接到指定主机上的指定端口号
            s = new Socket(inetAddress ,8080);
            pw =new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
            br =new BufferedReader(new InputStreamReader(s.getInputStream()));
            pw.print("链接网络服务");

//            while(true){
////                OutputStream os = socket.getOutputStream();
////                os.write("您好，恭喜您中奖了！".getBytes("utf-8"));
////                os.close();
//
//            }
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    pw.println("传递数据: " + (count++));
                    pw.flush();
                }
            },0,100, TimeUnit.MILLISECONDS);


        } catch (IOException e) {
            e.printStackTrace();
            if (s != null ){
                try {
                    s.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null){
                pw.close();
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


}
